﻿import QtQuick 2.0
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import "../mainpage"
import "../components"

Item {

    id: root
    property int editable: 1            // 0：不可编辑 1：可编辑 2：不能编辑编号


    onHeightChanged: {
        if(visible){
            refresh()
        }
    }onWidthChanged: {
        if(visible){
            refresh()
        }

    }

    // public ============================================================================
    function setProgramInfo(info){
        programInfo = info
        refreshInfo()
    }
    function setProgramStep(step){
        programStep = step
        refreshStep()
    }

    function getProgramInfo(info){
        pageDetails.syncInfo()
        pageDetails.syncItem()
        return programInfo
    }function getProgramStep(step){
        pageDetails.syncInfo()
        pageDetails.syncItem()
        return programStep
    }


    // private ============================================================================
    BoxError{
        id: msgBox
    }
    property var programInfo: []
    property var programStep: []


    function refresh(){
        refreshInfo()
        refreshStep()
    }

    function refreshInfo(){        // 初始化空的程序
        editor_Id.setText(programInfo["Id"])
        editor_name.setText(programInfo["ProgramName"])
        editor_memo.setText(programInfo["Memo"])
        editor_temp.setText(programInfo["HotCoverTemp"])
        combo_hot.changeCurrentIndex(programInfo["HotCoverStatus"]==="开启" ? 0 : 1)
        if(programInfo["HotCoverStatus"]==="开启"){
            editor_temp.editable = true
        }else{
            editor_temp.editable = false
        }
    }

    function refreshStep(){

        var headerList = layout_header.children
        var controllerList = layout_controller.children

        printProgramStep()

        // 黑条
        var headerInfo = []
        for(var i = programStep.length-1; i >= 0;  ){
            if(programStep[i]["CycleNumber"].toString() === "0"){
                headerInfo.unshift({
                                       "startStep": i+1,
                                       "endStep": i+1,
                                       "cycleNum": Number(programStep[i]["CycleNum"])
                                   })
                controllerList[i].collectable = false
                controllerList[i].isCollect = false
                i --
            }else{
                headerInfo.unshift({
                                       "startStep": Number(programStep[i]["CycleNumber"]),
                                       "endStep": i+1,
                                       "cycleNum": Number(programStep[i]["CycleNum"])
                                   })
                for(var j = i; j >= Number(programStep[i]["CycleNumber"]) - 1; j --){
                    controllerList[j].collectable = true
                    controllerList[j].isCollect = programStep[j]["IsCollect"]==="是" ? true : false
                }
                i = Number(programStep[i]["CycleNumber"]) - 2

            }

        }
        var stepCount = 0
        for(var i = 0; i < headerList.length; i ++){
            if (i >= headerInfo.length){
                headerList[i].visible = false
            }else{
                headerList[i].visible = true
                headerList[i].x = stepCount * 215*dp
                headerList[i].startStep = headerInfo[i]["startStep"]
                headerList[i].endStep = headerInfo[i]["endStep"]
//                headerList[i].cycleNum = headerInfo[i]["cycleNum"]
                headerList[i].setCycleNum(headerInfo[i]["cycleNum"])
                stepCount += headerInfo[i]["endStep"] - headerInfo[i]["startStep"] + 1
            }
        }

        // 控制器
        for(var i = 0; i < controllerList.length; i ++){
            if(i >= programStep.length){
                controllerList[i].visible = false
            }else{
                controllerList[i].visible = true
                controllerList[i].temperature = programStep[i]["Temperature"]
                controllerList[i].time = programStep[i]["ExecutionTime"]
                controllerList[i].rate = programStep[i]["Rate"]
                controllerList[i].step = i + 1
                controllerList[i].refresh()
            }
        }
    }


    function printProgramStep(){
        console.log("当前扩增程序步骤:")
        for(var i = 0; i < programStep.length; i ++){
            console.log(i+1, programStep[i]["CycleNumber"], programStep[i]["CycleNum"], programStep[i]["IsCollect"])
        }
    }

    function syncItem(){
        var controllerList = layout_controller.children
        for(var i = 0; i < programStep.length; i ++){
            programStep[i]["Temperature"] = controllerList[i].temperature
            programStep[i]["ExecutionTime"] = controllerList[i].time
            programStep[i]["Rate"] = controllerList[i].rate
        }

        var headerList = layout_header.children
        var cycleNumList = []
        for(var i = 0; i < headerList.length; i ++){
            if(headerList[i].stepNum > 1){
                cycleNumList.push(headerList[i].cycleNum)
            }
        }
        var p = 0
        for(var i = 0; i < programStep.length; i ++){
            if(programStep[i]["CycleNumber"].toString() !== "0"){
                programStep[i]["CycleNum"] = cycleNumList[p]
                p ++
            }
        }
    }
    function syncInfo(){

        programInfo["Id"] = editor_Id.getText()
        programInfo["ProgramName"] = editor_name.getText()
        programInfo["Memo"] = editor_memo.getText()
        programInfo["HotCoverTemp"] = editor_temp.getText()
        programInfo["HotCoverStatus"] = combo_hot.getText()
    }

    function addStep(step){             // 步骤操作 - 增加
        syncItem()
        if(programStep.length >= 6){
            msgBox.setText("最多包含6个扩增步骤")
            msgBox.show()
            return
        }
        var idx = step - 1
        programStep.splice(idx, 0, {
                                "StepNum": step,
                                "Temperature": 50,
                                "ExecutionTime": 10,
                                "CycleNumber": 0,
                                "CycleNum": 1,
                                "Id": "abc"+Math.random().toString(),
                                "Rate": 4,
                                "IsCollect": "否"
                            })
        for(var i = idx + 1; i < programStep.length; i ++){
            programStep[i]["StepNum"] = Number(programStep[i]["StepNum"]) + 1
            if(programStep[i]["CycleNumber"].toString()!=="0" && Number(programStep[i]["CycleNumber"]) >= step){
                programStep[i]["CycleNumber"] = Number(programStep[i]["CycleNumber"]) + 1
            }
        }
        refreshStep()
    }function delStep(step){             // 步骤操作 - 删除

        syncItem()
        if(programStep.length <= 1){
            msgBox.setText("至少保留一个扩增步骤")
            msgBox.show()
            return
        }

        var idx = step - 1
        // 为扩增步骤的结尾
        if(idx !== 0 && programStep[idx]["CycleNumber"].toString() !== "0"){
            programStep[idx-1]["CycleNumber"] = programStep[idx]["CycleNumber"].toString()
            if(programStep[idx-1]["CycleNumber"].toString() === programStep[idx-1]["StepNum"].toString()){
                programStep[idx-1]["CycleNumber"] = "0"
                programStep[idx-1]["CycleNum"] = "1"
            }
        }
        // 为扩增步骤开头，切扩增只有两个步骤
        if(idx+1 < programStep.length && programStep[idx+1]["CycleNumber"].toString()===step.toString()){
            programStep[idx+1]["CycleNumber"] = 0
            programStep[idx+1]["CycleNum"] = 1
        }

        programStep.splice(idx, 1)
        for(var i = idx; i < programStep.length; i ++){
            programStep[i]["StepNum"] = Number(programStep[i]["StepNum"]) -1
            if(Number(programStep[i]["CycleNumber"]) > step){
                programStep[i]["CycleNumber"] = Number(programStep[i]["CycleNumber"]) - 1
            }
        }
        refreshStep()
    }

    function expandLeft(step){          // 步骤操作 - 向左合并
        syncItem()
        var idx = step - 1
        if(idx === 0){
            return
        }
        var startStep = step-1
        if(programStep[idx-1]["CycleNumber"].toString() !== "0"){
            startStep = Number(programStep[idx-1]["CycleNumber"])
            programStep[idx-1]["CycleNumber"] = 0
            programStep[idx-1]["CycleNum"] = 1
        }
        for(let i = idx+1; i < programStep.length; i ++){
            if(programStep[i]["CycleNumber"].toString() === step.toString()){
                programStep[i]["CycleNumber"] = startStep
                refreshStep()
                return
            }
        }
        programStep[idx]["CycleNumber"] = startStep
        programStep[idx]["CycleNum"] = 2
        refreshStep()

    }function expandRight(step){         // 步骤操作 - 向右合并
        syncItem()
        var idx = step - 1
        if(idx >= programStep.length-1){
            return
        }
        var startStep
        var cycleNum = 2
        if(programStep[idx]["CycleNumber"].toString()==="0"){
            startStep = step
        }else{
            startStep = programStep[idx]["CycleNumber"].toString()
            programStep[idx]["CycleNumber"] = 0
            programStep[idx]["CycleNum"] = 1
        }
        for(let i = idx+1; i < programStep.length; i ++){
            if(programStep[i]["CycleNumber"].toString() === (step+1).toString()){
                programStep[i]["CycleNumber"] = startStep
                refreshStep()
                return
            }
        }
        programStep[idx+1]["CycleNumber"] = startStep
        programStep[idx+1]["CycleNum"] = 2
        refreshStep()
    }
    function contractLeft(step){        // 步骤操作 - 分离左边的
        syncItem()
        var idx = step - 1
        // 当前的变为单个的
        programStep[idx]["CycleNumber"] = 0
        programStep[idx]["CycleNum"] = 1

        // 查找右面的变更起始循环
        for(let i = idx + 1; i < programStep.length; i ++){
            if(programStep[i]["CycleNumber"].toString() === "0")    continue
            if((i).toString() === (idx + 1).toString()){
                programStep[i]["CycleNumber"] = 0
                programStep[i]["CycleNum"] = 1
            }else{
                programStep[i]["CycleNumber"] = step+1
            }
            break
        }
        refreshStep()

    }function contractRight(step){      // 步骤操作 - 分离右面的
        syncItem()
        var idx = step - 1
        if(programStep[idx]["CycleNumber"].toString() !== (step-1).toString()){
            programStep[idx-1]["CycleNumber"] = programStep[idx]["CycleNumber"]
            programStep[idx-1]["CycleNum"] =    programStep[idx]["CycleNum"]
        }else{
            console.log("当前元素的CycleNumber:", programStep[idx]["CycleNumber"].toString(), "前一个元素的Step:", step-1)
        }

        programStep[idx]["CycleNumber"] = 0
        programStep[idx]["CycleNum"] = 1
        refreshStep()
    }


    function changeCollect(step, state){
        syncItem()
        var idx = step - 1
        if(state === false){
            programStep[idx]["IsCollect"] = "否"
        }else{
            for(let i = 0; i < programStep.length; i ++){
                programStep[i]["IsCollect"] = "否"
            }
            programStep[idx]["IsCollect"] = "是"
        }
        refreshStep()
    }

    property var stepInfo

    onVisibleChanged: {
        if(visible){
            refreshStep()
        }
    }


    anchors.fill: parent

    Rectangle{               // 程序
        anchors.fill: parent
        x: 0
        y: 0


        Rectangle{              // 程序信息
            x:20*dp
            y:20*dp
            height: 40*dp
            width: parent.width-40*dp
            Row{
                x: 10*dp
                spacing: 35*dp

                LineEditor{
                    id: editor_Id
                    title: "编号"
                    required: true
                    editWidth: 70*dp
                    textWidth: 40*dp
                    onTextChanged: {
                    }
                    digit: true
                    inputMaxLength: 3
                    editable: root.editable === 1
                }
                LineEditor{
                    id: editor_name
                    title: "程序名称"
                    required: true
                    editWidth: 200*dp
                    textWidth: 75*dp
                    onTextChanged: {
                    }
                    inputMaxLength: 20
                    editable: root.editable !== 0
                }
                LineEditor{
                    id: editor_memo
                    title: "备注"
                    editWidth: 220*dp
                    inputMaxLength: 30
                    textWidth: 40*dp
                    onTextChanged: {
                    }
                    editable: root.editable !== 0
                }

                CustomComboBox{
                    id: combo_hot
                    editWidth: 100*dp
                    textWidth: 40*dp
                    title: "热盖"
                    model: ["开启", "关闭"]
                    onCurrentText: {
                        if(text==="关闭"){
                            editor_temp.setText("0")
                            editor_temp.editable=false
                        }else{
                            editor_temp.editable=true
                        }
                    }
                    editable: root.editable !== 0
                }

                LineEditor{
                    id: editor_temp
                    title: "热盖温度(°C)"
                    editWidth: 100*dp
                    textWidth: 95*dp
                    intflag: true
                    onTextChanged: {
                        if(!visible) return
                        if(Number(getText()) > 150 || Number(getText()) < 0){
                            mainwindow.showToast("热盖温度范围为0至150°C", 1)
                            setText(Math.max(Math.min(Number(getText()), 150), 0))
                        }
                    }
                    editable: root.editable !== 0
                }

            }
        }

        Rectangle{          // 下面的控制器
            id: layout_controller
            color: "#F7F7FA"
            height: Math.min(parent.height - 100*dp, 600*dp) - 100*dp
            width: parent.width - 60*dp
            y: 190*dp
            x: 30*dp
            StepItemController{
                x: 0
                isEditable: root.editable !== 0
            }StepItemController{
                x: 215*dp
                isEditable: root.editable !== 0
            }StepItemController{
                x: 2*215*dp
                isEditable: root.editable !== 0
            }StepItemController{
                x: 3*215*dp
                isEditable: root.editable !== 0
            }StepItemController{
                x: 4*215*dp
                isEditable: root.editable !== 0
            }StepItemController{
                x: 5*215*dp
                isEditable: root.editable !== 0
            }
        }
        Rectangle{          // 黑条
            id: layout_header
            y: 90*dp
            x: 30*dp
            height: 100*dp
            width: parent.width - 60*dp
            color: "#F7F7FA"

            StepItemHeader{
                isEditable: root.editable > 0
            }StepItemHeader{
                isEditable: root.editable > 0
            }StepItemHeader{
                isEditable: root.editable > 0
            }StepItemHeader{
                isEditable: root.editable > 0
            }StepItemHeader{
                isEditable: root.editable > 0
            }StepItemHeader{
                isEditable: root.editable > 0
            }

        }


    }
}
